using Microsoft.AspNetCore.Identity;
using PYNET.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using Newtonsoft.Json;
using PYNET.Utils;
using Microsoft.AspNetCore.StaticFiles;
using PYNET.Data;

namespace PYNET.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        private readonly ArticleSystemDbContext _context;
        private readonly SignInManager<User> _signInManager;
        private readonly UserManager<User> _userManager;
        private readonly RoleManager<TIdentityRole> _roleManager;
        private readonly IWebHostEnvironment _env;
        public AccountController(
            SignInManager<User> signInManager,
            UserManager<User> userManager,
            RoleManager<TIdentityRole> roleManager,
            ArticleSystemDbContext context,
            IWebHostEnvironment env)
        {
            _signInManager = signInManager;
            _userManager = userManager;
            _roleManager = roleManager;
            _context = context;
            _env = env;
        }
        public IActionResult Index()
        {
            return RedirectToAction("Login", "Account");
        }

        [AllowAnonymous]
        public IActionResult AccessDenied()
        {
            return View();
        }

        [AllowAnonymous]
        public IActionResult Login()
        {
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel loginViewModel,string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(loginViewModel);
            }
            var user = await _userManager.FindByNameAsync(loginViewModel.UserName);
            if (user != null)
            {
                var result = await _signInManager
                    .PasswordSignInAsync(user, loginViewModel.PassWord, false, false);

                if (result.Succeeded)
                {
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    return RedirectToAction("Index", "Home");
                }
            }
            ModelState.AddModelError("", "用户名/密码错误");
            return View(loginViewModel);

        }

        [AllowAnonymous]
        public IActionResult Register()
        {
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Register(RegisterViewModel registerViewModel)
        {
            if (ModelState.IsValid)
            {
                if(registerViewModel.InvCode!= "" || registerViewModel.InvCodea != "")
                {
                    ModelState.AddModelError("", "邀请问题错误!");
                    return View(registerViewModel);
                }
                DateTime now = DateTime.Now;
                var user = new User
                {
                    UserName = registerViewModel.UserName,
                    Email = registerViewModel.Email,
                    RegistTime = now.ToString("yyyy-MM-dd"),
                    HeadPicture = "DefaultHeadPicture.jpg"
                };
                var result = await _userManager.CreateAsync(user, registerViewModel.Password);
                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, "User");
                    return RedirectToAction("Index", "Home");
                }
            }
            //ModelState.AddModelError("", "填写错误");
            return View(registerViewModel);
        }

        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            return RedirectToAction("Index", "Home");
        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> CheckUserName()
        {
            string name = Request.Form["UserName"];
            if (name == "null")
            {
                return new JsonResult("用户名不能为空");
            }
            var user = await _userManager.FindByNameAsync(name);
            if (user == null)
            {
                return new JsonResult("OK");
            }
            else
            {
                return new JsonResult("Exist");
            }
        }

        public async Task<IActionResult> MyAccount()
        {
            var user =await _userManager.GetUserAsync(HttpContext.User);
            var comments = await _context.Comments.Where(s => s.UId.Equals(user.Id)).ToListAsync();
            MyAccountViewModel s = new MyAccountViewModel { comments=comments };
            return View(s);
        }
        public async Task<IActionResult> ChangeUserName(MyAccountViewModel changeUserName)
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);
            if (user == null)
            {
                return RedirectToAction("Index", "Home");
            }
            user.UserName = changeUserName.UserName;
            var result = await _userManager.UpdateAsync(user);
            if (result.Succeeded)
            {
                return RedirectToAction("Index", "Home");
            }
            ModelState.AddModelError(string.Empty, "Fail to update");
            return RedirectToAction("MyAccount", "Account", changeUserName);
        }

        [HttpPost]
        public async Task<IActionResult> ChangeUserPassword(MyAccountViewModel changePassword)
        {
            var CurrenUser = await _userManager.GetUserAsync(HttpContext.User);
            if (ModelState.IsValid)
            {
                var result = await _userManager.ChangePasswordAsync(CurrenUser, changePassword.OldPassword, changePassword.Password);
                if (result.Succeeded)
                {
                    return RedirectToAction("Login", "Account");
                }
            }
            ModelState.AddModelError("", "前后密码不一致或原密码错误");
            return RedirectToAction("MyAccount", "Account",changePassword);
        }

        /*[HttpPost]
        public async Task<IActionResult> ChangeUserHeadPicture()
        {
            var file = Request.Form.Files[0];
            if (file == null)
            {
                return RedirectToAction("Index", "Home");
            }
            var size = file.Length;
            if (size > 0 && size < 10000)
            {

                var FileName = DateTime.Now.ToString("MMddHHmmss") + ".jpg";
                var FilePath = Path.Combine("StaticFiles", FileName);

                using (var stream = System.IO.File.Create(FilePath))
                {
                    await file.CopyToAsync(stream);
                }
                var user = await _userManager.GetUserAsync(HttpContext.User);
                user.HeadPicture = FileName;
                await _userManager.UpdateAsync(user);
            }
            else
            {
                ModelState.AddModelError("", "文件大小不合法");
            }
            return Ok();
        }*/ //废弃

        [HttpGet]
        public ActionResult UpLoadFile()
        {
            return View();
        }

        public async Task<IActionResult> UpLoadFile(string tailorInfo)
        {
            var success = false;
            var message = string.Empty;
            var newImage = string.Empty;
            try
            {
                var tailorInfoEntity = JsonConvert.DeserializeObject<TailorInfo>(tailorInfo);
                tailorInfoEntity.PictureWidth = tailorInfoEntity.PictureWidth.Replace("px", "");
                tailorInfoEntity.PictureHeight = tailorInfoEntity.PictureHeight.Replace("px", "");

                var Ifile = Request.Form.Files[0];
                var file = Ifile.OpenReadStream();
                if (file != null && file.Length != 0)
                {
                    var FileName = DateTime.Now.ToString("MMddHHmmss") + ".jpg";
                    newImage = ImageHelper.TailorImage(file, tailorInfoEntity, FileName);
                    var user = await _userManager.GetUserAsync(HttpContext.User);
                    user.HeadPicture = FileName;
                    await _userManager.UpdateAsync(user);

                    success = true;
                    message = "保存成功";
                }
            }
            catch (Exception ex)
            {
                message = "保存失败" + ex.Message;
            }

            return Json(new { success = success, message = message, newImage = newImage });
        }

        [HttpPost]
        public async Task<IActionResult> UserSelfDelete()
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);
            if (user == null)
            {
                ModelState.AddModelError("", "不存在此用户");
                return View();
            }
            await _signInManager.SignOutAsync();
            var result = await _userManager.DeleteAsync(user);
            if (result.Succeeded)
            {

                return RedirectToAction("Index", "Home");
            }
            ModelState.AddModelError("", "修改失败");
            return View();
        }
        [AllowAnonymous]
        public async Task<IActionResult> GetUserHead(int id)
        {
            /*var addUrl = FileName;
            var stream = System.IO.File.OpenRead(addUrl);
            var FileExt = System.IO.Path.GetExtension(FileName);
            var provider = new FileExtensionContentTypeProvider();
            var memi = provider.Mappings[FileExt];
            return File(stream, memi, System.IO.Path.GetFileName(addUrl));*/
            var user = await _userManager.FindByIdAsync(id.ToString());
            if (user == null)
            {
                var prov = new FileExtensionContentTypeProvider();
                var mmi = prov.Mappings[".jpg"];
                var ls = Path.Combine(
                 _env.ContentRootPath, "StaticFiles", "UserPic", "DefaultHeadPicture.jpg");
                return PhysicalFile(ls, mmi);
            }
            var uid = user.HeadPicture;
            var FileExt = System.IO.Path.GetExtension(uid);
            var provider = new FileExtensionContentTypeProvider();
            var memi = provider.Mappings[FileExt];
            var filePath = Path.Combine(
            _env.ContentRootPath, "StaticFiles","UserPic", uid);
            return PhysicalFile(filePath, memi);
        }
        public IActionResult ArticleCreate()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> ArticleCreate([Bind("Title,Introduce,Content,ArticlePicture")] ArticleRequest articleRequest)
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);
            articleRequest.UId = user.Id;
            articleRequest.UserName = user.UserName;
            articleRequest.status = 0;
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(articleRequest);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(MyAccount));
                }
            }
            catch
            {
                ModelState.AddModelError("", "遇到了某些神奇的错误导致失败");
            }
            return View(articleRequest);
        }
    }
}
